<template>
    <div class="table_container">
        <ZwSearchForm row-num="2" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetch()"
            @selection-change="onSelectionChange">
            <template #headerOperate>
                <el-button :disabled="selectid.length == 0" @click="batchGive">批量分配</el-button>
                <!-- <el-button @click="batchdel" :disabled="selectid.length == 0">批量放弃</el-button> -->
                <el-button @click="router.push('/customer/manage/sea/importDetail')">导入记录</el-button>
                <el-dropdown style="margin-left: 10px">
                    <el-button type="primary">
                        添加客户<el-icon class="el-icon--right">
                            <arrow-down />
                        </el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="singleAdd">单个添加</el-dropdown-item>
                            <el-dropdown-item @click="openExport">批量导入</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </template>
        </ZwTable>

        <customerPopover
            v-model="isShowPopover"
            :popover-contacts="popoverContacts"
            :popover-top="popoverTop"
            :popover-left="popoverLeft" />

        <!-- 添加客户（个人客户 & 企业客户） -->
        <AddCustomer ref="AddCustomerRef" v-model="addCustomerVisible" :seas_id="props.seas_id" @submit="submitData" />

        <!-- 添加个人客户弹框 -->
        <!-- <Dialog :appDialog="appDialog">
      <div class="allcontent">
        <div class="content">
          <div :class="[clubChoose == 1 ? 'column both' : 'column']" @click="addCustomer(1)"><img
              src="@/assets/customer/person.png" /><span class="text">个人客户</span></div>
          <div :class="[clubChoose == 2 ? 'column both' : 'column']" @click="addCustomer(2)"><img
              src="@/assets/customer/customer.png" /><span class="text">企业客户</span></div>
        </div>
      </div>
      <div class="tiptext">
        <el-checkbox v-model="ischecked">勾选之后，将不再提醒</el-checkbox>
      </div>
    </Dialog>
    <NewClub :open="openPerson" :seas_id="props.seas_id" :rowid="rowid" :isEdit="isEdit" @close="closeNewClub"
      @submit="submitData"></NewClub>

    <NewClubCompany :open="openCompany" :seas_id="props.seas_id" :isEdit="isEdit" :rowid="rowid" @close="closeNewClub"
      @submit="submitData"></NewClubCompany> -->

        <AddBatch
            :isopen="isopenBatch"
            :seas_id="props.seas_id"
            @close="isopenBatch = false"
            @submit="reset()"></AddBatch>

        <!-- 删除弹框 -->
        <Dialog :app-dialog="secondDialog">
            <div class="dialog_content">{{ alertTips }}</div>
        </Dialog>
        <!-- 放弃弹框 -->
        <Dialog :app-dialog="abandonDialog">
            <div class="abandon">
                <div class="photo"><img src="@/assets/customer/warn.png" /></div>
                <div class="abandonstyle">
                    <div style="margin-bottom: 16px">放弃客户后，客户将不能被员工认领、不能被公海分配和回收</div>
                    <el-form :model="abandonData" label-width="auto">
                        <el-form-item label="放弃原因" required>
                            <el-select v-model="abandonData.invalid_id" placeholder="请选择放弃原因">
                                <el-option
                                    v-for="(item, index) in reasonListData"
                                    :key="index"
                                    :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </Dialog>
        <ZWDepart ref="DepartRef" type="1" @submit="getDepart" />
        <ClubDrew :clubopen="clubopen" :rowid="rowid" :title="title" @close="close"></ClubDrew>

        <!-- 导入客户的弹框 -->
        <ImportCustomer ref="ImportCustomerRef" :multiple="true" @save="getListFun" />
    </div>
</template>

<script setup lang="tsx">
import { ref, reactive, computed } from 'vue';
import { ElButton, ElLoading, ElMessage } from 'element-plus';
import ZwTable from '@/components/zw/table/Table';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZWDepart from '@/components/ZWDepart.vue';
import Dialog from '@/components/Dialog.vue';
import NewClub from './NewClub.vue';
import NewClubCompany from './NewClubCompany.vue';
import ClubDrew from './ClubDrew.vue';
import AddBatch from './AddBatch.vue';
import customerPopover from './customerPopover.vue';

import AddCustomer from '@/components/customerCenter/AddCustomer.vue';

import ImportCustomer from '@/view/customer/manage/list/components/ImportCustomer.vue';

import {
    backList,
    setSettings,
    getSettings,
    delData,
    reasonList,
    setAbandon,
    distribution
} from '@/api/customer/clubManage/commonSea';

import { batchAssignStaff } from '@/api/customerCenter';

import { customerList } from '@/api/customerCenter/customerSea';

import { deepCopy } from '@/utils/helper';
import { getSetionId } from '@/utils/utils';
import router from '@/router';
import { parabolaAnimation } from '@/utils/parabola';
import customerSrc from '../../../../../assets/customer/customer.png';

const props = defineProps(['seas_id', 'seaName']);
const tableRef = ref<HTMLElement | null>(null);
const defaultParams = {};
const abandonData = reactive({ clue_list: [], invalid_id: '' });
const clubopen = ref(false); //流转记录抽屉是否打开
const title = ref(''); //流转记录抽屉标题
const isopenBatch = ref(false); //判断批量添加弹框是否打开
const selectid = ref([]);
const DepartRef = ref(null);
const reasonListData = ref([]);

const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const openPerson = ref(false);
const openCompany = ref(false);
const ischecked = ref(false);
const clubChoose = ref(0);
const rowid = ref(null); //行客户id
const isEdit = ref(false); //点击新增个人客户打开新增客户为false 表格操作栏点击编辑为false
const isbatchDel = ref(false); //判断是否是批量删除
const singleStaff = ref([]); //行分配员工
const batchStaff = ref([]); //批量分配员工
const whichOpen = ref(1); //判断打开那个员工组件 1为行员工组件 2为批量员工组件
const assignData = reactive({ customer_list: [], work_user_list: [] });

const isShowPopover = ref<boolean>(false);
const popoverContacts = reactive([]);
const popoverTop = ref<number>(0);
const popoverLeft = ref<number>(0);

const addCustomerVisible = ref<boolean>(false);
const AddCustomerRef = ref<any>(null);

// 打开导入客户的弹框
const ImportCustomerRef = ref<any>(null);
const openImportCustomer = () => {
    ImportCustomerRef.value.appDialog.visible = true;
};
const getListFun = e => {
    parabolaAnimation(e);
    reset();
};

const openExport = () => {
    openImportCustomer();
    // isopenBatch.value = true
};

const cancelHandel = () => {
    appDialog.visible = false;
};
const submitHandel = () => {
    if (!clubChoose.value) {
        ElMessage.warning('请选择客户类型');
    } else if (clubChoose.value == 1) {
        // 选择个人类型
        setClub(clubChoose.value);
        appDialog.visible = false;
        openPerson.value = true;
    } else {
        // 选择客户类型
        setClub(clubChoose.value);
    }
};
const setClub = (data: any) => {
    setSettings({ clue_type: data, remember: ischecked.value });
};
const appDialog = reactive({
    visible: false,
    title: '选择客户类型',
    width: '500px',
    isHiddenFoot: true
    // cancel: cancelHandel,
    // submit: submitHandel,
    // cancelText: '取消',
    // submitText: '确定'
});
const alertTips = ref('');
const submitSecond = () => {
    delData({ clue_list: [rowid.value] }).then(res => {
        secondDialog.visible = false;
        reset();
        ElMessage.success('删除成功');
    });
};
const cancelSecond = () => {
    secondDialog.visible = false;
};
const secondDialog = reactive({
    visible: false,
    title: '删除提醒',
    width: '500px',
    cancel: cancelSecond,
    submit: submitSecond,
    cancelText: '取消',
    submitText: '确定'
});
const submitAbandon = () => {
    if (!abandonData.invalid_id) {
        ElMessage.warning('请选择放弃原因');
        return;
    }
    if (!isbatchDel.value) {
        setAbandon({ clue_list: [rowid.value], invalid_id: abandonData.invalid_id }).then(res => {
            abandonDialog.visible = false;
            reset();
            ElMessage.success('放弃成功');
        });
    } else {
        setAbandon({ ...abandonData, clue_list: selectid.value }).then(res => {
            abandonDialog.visible = false;
            reset();
            ElMessage.success('放弃成功');
        });
    }
};
const cancelAbandon = () => {
    abandonDialog.visible = false;
};
const abandonDialog = reactive({
    visible: false,
    title: '删除提醒',
    width: '500px',
    cancel: cancelAbandon,
    submit: submitAbandon,
    cancelText: '取消',
    submitText: '确定'
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'name',
        label: '客户信息',
        minWidth: 300,
        render: ({ row }) =>
            row.type == 1 ? (
                <div style="display:flex;align-items:center;">
                    <div style="width:38px;height:38px;background:#eee;margin-right:8px;border-radius:50%">
                        <img style="width:38px;height:38px;" src={row.avatar} alt="" />
                    </div>
                    <div style="display:flex;align-items:center;">
                        <el-tooltip content={row.name} placement="top">
                            <p style="line-height:1;minWidth:1px;maxWidth:230px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                                {row.name}
                            </p>
                        </el-tooltip>
                        {row.sex == 1 ? (
                            <div style="margin-left:6px;width:20px;line-height:20px;background:#668cff;border-radius:50%;color:#fff;text-align:center;">
                                男
                            </div>
                        ) : row.sex == 1 ? (
                            <div style="margin-left:6px;width:20px;line-height:20px;background:#ffd966;border-radius:50%;color:#fff;text-align:center;">
                                女
                            </div>
                        ) : (
                            <div style="margin-left:6px;width:20px;line-height:20px;background:#ff80ff;border-radius:50%;color:#fff;text-align:center;">
                                未
                            </div>
                        )}
                    </div>
                    {row.is_protected == 1 ? (
                        <img style="width:20px;height:20px;margin-left:6px" src="/static/protect.png" />
                    ) : (
                        ''
                    )}
                </div>
            ) : (
                <div style="display:flex;align-items:center;">
                    <div style="width:38px;height:38px;background:#eee;margin-right:8px;border-radius:50%">
                        <img style="width:38px;height:38px;" src={row.avatar} alt="" />
                    </div>
                    <div>
                        <el-tooltip content={row.name} placement="top">
                            <p style="line-height:1;margin-bottom:8px;minWidth:1px;maxWidth:230px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                                {row.name}
                            </p>
                        </el-tooltip>
                        <h5 style="color:#888;font-size:12px;line-height:1;">
                            共{row?.contact?.length}个联系人&nbsp;
                            {row?.contact?.length ? (
                                <span
                                    style="color:#1890FF;font-size:12px;cursor:pointer;"
                                    onClick={checkContacts.bind(this, row)}>
                                    查看
                                </span>
                            ) : (
                                ''
                            )}
                        </h5>
                    </div>
                    {row.is_protected == 1 ? (
                        <img style="width:20px;height:20px;margin-left:6px" src="/static/protect.png" />
                    ) : (
                        ''
                    )}
                </div>
            )
    },
    {
        prop: 'mobile',
        label: '手机号',
        width: 200,
        render({ row }) {
            return row?.mobile || '--';
        }
    },
    {
        prop: 'type',
        label: '客户类型',
        width: 200,
        render({ row }) {
            if (row.type == 1) {
                return '个人客户';
            } else if (row.type == 2) {
                return '企业客户';
            } else {
                return '--';
            }
        }
    },
    {
        prop: 'work_user_name',
        label: '原归属员工',
        width: 200,
        render({ row }) {
            return row?.work_user_name || '--';
        }
    },
    {
        prop: 'return_reason',
        label: '退回原因',
        width: 200,
        render({ row }) {
            return row?.return_reason || '--';
        }
    },
    {
        prop: 'user_name',
        label: '操作人',
        width: 200,
        render({ row }) {
            return row?.user_name || '--';
        }
    },
    {
        prop: 'return_at',
        label: '退回时间',
        minWidth: 220,
        render({ row }) {
            return row?.return_at || '--';
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 140,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return (
                <>
                    <ElButton
                        size="small"
                        v-show={row.allow_distribution == 1}
                        onClick={() => {
                            rowid.value = row.id;
                            DepartRef.value.multiple = false;
                            DepartRef.value.departVisble = true;
                            whichOpen.value = 1;
                            DepartRef.value.selectedMember = [...singleStaff.value];
                        }}>
                        分配
                    </ElButton>
                    <ElButton
                        size="small"
                        onClick={() => {
                            rowid.value = row.id;
                            title.value = `【${props.seaName}】-【${row.name}/${row.mobile}】的分配记录`;
                            clubopen.value = true;
                        }}>
                        分配记录
                    </ElButton>
                </>
            );
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const searchOption = computed(() => {
    return [
        {
            label: '客户名称',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '请输入客户名称搜索'
        },
        {
            label: '客户手机',
            name: 'mobile',
            value: '',
            type: 'input',
            placeholder: '请输入客户手机号搜索'
        },
        {
            label: '退回时间',
            name: 'return_at',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const personAdd = () => {
    clubChoose.value = 0;
    appDialog.visible = true;

    // openPerson.value = false
    // getSettings().then((res) => {
    //   if (!res.clue_type) {
    //     //未设置
    //     appDialog.visible = true
    //     clubChoose.value = 0
    //   } else if (res.clue_type == 1) {
    //     //设置为个人
    //     isEdit.value = false
    //     openPerson.value = true
    //   } else {
    //     //设置为客户，还没有开发
    //   }
    // })
};

const addCustomer = (clubChooseNum: number): void => {
    clubChoose.value = clubChooseNum;
    isEdit.value = false;
    appDialog.visible = false;
    switch (clubChooseNum) {
        case 1:
            openPerson.value = true;
            break;
        case 2:
            openCompany.value = true;
            break;
    }
};

const getids = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(props.seas_id);
        }, 1);
    });
};

const fetch = async () => {
    const cust_seas_id = await getids();
    const seas_type = 3;
    // const page_size = 15
    return [{ cust_seas_id, seas_type }, customerList];
};

const singleAdd = () => {
    AddCustomerRef.value.drawerData.userInfo = null;
    AddCustomerRef.value.drawerData.seas_id = props.seas_id;
    AddCustomerRef.value.drawerData.controlType = 'create';
    addCustomerVisible.value = true;
};

//查询
const search = (v: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = v;
};
//清空
const reset = () => {
    tableRef.value?.clearSelection();
    state.searchParams = deepCopy(defaultParams);
};

const checkContacts = (row: any, $event: any): void => {
    const { contact: contact = [] } = row;

    const { x, y } = $event;
    isShowPopover.value = true;

    popoverTop.value = y;
    popoverLeft.value = x;

    popoverContacts.splice(0);
    popoverContacts.push(...contact);
};

const getReasonList = () => {
    reasonList({ page: 1, page_size: 1000 }).then(res => {
        reasonListData.value = res.data;
    });
};
// 获取放弃原因列表
const onSelectionChange = (data: any) => {
    selectid.value = getSetionId('id', data);
};
const batchdel = () => {
    isbatchDel.value = true;
    getReasonList();
    abandonDialog.title = '批量放弃';
    abandonDialog.visible = true;
};
// 获取部门成员
const getDepart = (res: any, isCancel: boolean) => {
    if (isCancel) {
        DepartRef.value.departVisble = false;
        return;
    }
    if (whichOpen.value == 1) {
        singleStaff.value = res;
        assignData.work_user_list = getSetionId('id', singleStaff.value);
        assignData.customer_list = [];
        assignData.customer_list.push(rowid.value);
        batchAssignStaff(assignData).then(res => {
            ElMessage.success('分配成功');
            reset();
            singleStaff.value = [];
        });
    } else {
        batchStaff.value = res;
        assignData.work_user_list = getSetionId('id', batchStaff.value);
        assignData.customer_list = selectid.value;
        batchAssignStaff(assignData).then(res => {
            ElMessage.success('批量分配成功');
            reset();
            batchStaff.value = [];
        });
    }
    DepartRef.value.departVisble = false;
};
//批量分配
const batchGive = () => {
    whichOpen.value = 2;
    DepartRef.value.multiple = false;
    DepartRef.value.departVisble = true;
    DepartRef.value.selectedMember = [...batchStaff.value];
};
const close = () => {
    clubopen.value = false;
};
const closeNewClub = () => {
    openPerson.value = false;
};
const submitData = () => {
    // openPerson.value = false
    reset();
};
</script>
<style scoped lang="scss">
.table_container {
    height: calc(100vh - 308px);
    display: flex;
    flex-direction: column;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.tiptext {
    text-align: center;
}

.allcontent {
    padding: 24px 38px;
}

.abandon {
    display: flex;
    padding: 33px 0;

    img {
        width: 36px;
        height: 36px;
    }

    .photo {
        display: flex;
        align-items: center;
        margin-right: 5px;
    }

    .abandonstyle {
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        :deep .el-form-item {
            margin-bottom: 0;
        }
    }
}

.content {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    & > div {
        cursor: pointer;
    }

    .both {
        border: 1px solid #ff6b00 !important;
    }

    .column {
        display: flex;
        flex-direction: column;
        align-items: center;
        border: 1px solid #eaeaea;
        border-radius: 4px;
        padding: 22px 40px;

        .text {
            margin-top: 11px;
            font-weight: 500;
            color: #33302d;
        }
    }
}
</style>
